<template>
  <div class="category-section">
    <h2 class="category-title">{{ category.title }}</h2>
    <p v-if="category.body" class="category-description">{{ category.body }}</p>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="2" animated />
    </div>
    
    <div v-else-if="courses.length === 0" class="empty-container">
      <el-empty description="该分类下暂无课程">
        <el-button type="primary" @click="$router.push('/add-course')">
          添加课程
        </el-button>
      </el-empty>
    </div>
    
    <div v-else class="course-grid">
      <CourseCard 
        v-for="course in courses" 
        :key="course.id" 
        :course="course" 
      />
    </div>
    
    <!-- 调试信息 -->
    <div v-if="showDebugInfo" class="debug-info">
      <h4>调试信息:</h4>
      <p>分类ID: {{ category.id }}</p>
      <p>课程数量: {{ courses.length }}</p>
      <p>加载状态: {{ loading }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import CourseCard from './CourseCard.vue'
import * as api from '../services/api'
import { ElMessage } from 'element-plus'

const props = defineProps({
  category: {
    type: Object,
    required: true
  },
  showDebugInfo: {
    type: Boolean,
    default: false
  }
})

const courses = ref([])
const loading = ref(false)

const loadCourses = async () => {
  if (!props.category || !props.category.id) {
    console.warn('分类ID无效:', props.category)
    return
  }
  
  try {
    loading.value = true
    console.log('正在加载分类课程:', props.category.id)
    
    const response = await api.getCoursesByCategory(props.category.id)
    courses.value = Array.isArray(response) ? response : []
    
    console.log(`分类 ${props.category.title} 的课程:`, courses.value)
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error(`获取分类"${props.category.title}"的课程失败`)
    courses.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  console.log('CourseCategoryBlock 挂载，分类:', props.category)
  loadCourses()
})
</script>

<style scoped>
.category-section {
  margin-bottom: 40px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.category-description {
  color: #606266;
  font-size: 14px;
  margin-bottom: 20px;
  line-height: 1.5;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.loading-container, .empty-container {
  padding: 40px;
  text-align: center;
}

.debug-info {
  margin-top: 20px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.debug-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
}

.debug-info p {
  margin: 5px 0;
  font-size: 12px;
  color: #666;
}
</style>